package top.broncho.mvvm.util

import android.content.SharedPreferences
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.safeOffer

fun SharedPreferences.onPrefChange(): Flow<String> = callbackFlow<String> {
    val listener =
        SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
            safeOffer(key)
        }
    registerOnSharedPreferenceChangeListener(listener)
    awaitClose { unregisterOnSharedPreferenceChangeListener(listener) }
}.conflate()